$(() => {
   let INFO
   function download(url, name) {
      const download = document.getElementById('download')
      download.href = url
      download.download = name
      download.click()
   }
   function replaceState() {
      const newurl = location.href + '?id=' + INFO.id
      console.log(newurl);
      history.replaceState({
         path: newurl
      }, '', newurl);
   }
   // 编辑器
   const { Editor } = toastui
   const { codeSyntaxHighlight } = Editor.plugin;
   window.editor = new Editor({
      el: document.getElementById('editor'),
      previewStyle: 'vertical',
      height: '100%',
      hideModeSwitch: true,
      previewHighlight: false,
      initialEditType: 'markdown',
      plugins: [
         [codeSyntaxHighlight, { highlighter: Prism }]
      ],
      toolbarItems: []
   });
   let pushload = true
   $('.release').on('click', function () {
      if (pushload) {
         if (INFO) {
            pushload = false
            $('.cover-btn input').eq(INFO.cover_type).click()
            $('.textarea textarea').text(INFO.abstract)
            $('.push_article .type input').eq(INFO.type).click()
            $('.push_article .so input').eq(INFO.so).click()
            if (INFO.tag) {
               INFO.tag.split(' ').forEach(a => {
                  addTag(a)
               })
            }
            if (INFO.classifArr) {
               console.log(INFO.classif);
               INFO.classifArr.forEach(a => {
                  addClass(a.name, INFO.classif.includes(a.name))
               })
            }
            if (INFO.cover) {
               const cover = $('.cover-list .fmimage_box')
               INFO.cover.split(' ').forEach((a, i) => {
                  cover.eq(i).css('background-image', `url(/userupimage/${a})`).addClass('file').data('url', a)
               })
            }
         } else {
            pushload = false
            $.get('/api/info', res => {
               if (res.code == 200) {
                  res.classif.forEach(a => {
                     addClass(a.name)
                  })
               } else {
                  alterBlock(res.code)
               }
            })
         }
      }
   })
   $('.toastui-editor-main .toastui-editor-md-vertical-style .toastui-editor-md-splitter')
      .append($('.button-bar'))
   const title_input = $('#title')
   // 获取文章原文
   {
      let id = document.documentElement.getAttribute('data-id')
      if (id) {
         $.get('/api/article/info', { id }, res => {
            if (res.code == 200) {
               INFO = res.article
               INFO.classifArr = res.classif
               editor.setMarkdown(INFO.main)
               editor.moveCursorToStart()
               title_input.val(INFO.title)
               $('header .title .title-lenght').text(INFO.title.length)
            } else {
               location.href = '/editor'
            }
         })
      }
   }
   // 工具栏
   {
      const btns = $('.edit-Buttons .button-box')
      btns.eq(0).on('click', function () {
         editor.exec('bold')
      })
      btns.eq(1).on('click', function () { editor.exec('italic') })
      btns.eq(2).on('click', function () { editor.exec('heading', { level: 1 }) })
      btns.eq(3).on('click', function () { editor.exec('strike') })
      btns.eq(4).on('click', function () { editor.exec('bulletList') })
      btns.eq(5).on('click', function () { editor.exec('orderedList') })
      btns.eq(6).on('click', function () { editor.exec('taskList') })
      btns.eq(7).on('click', function () { editor.exec('blockQuote') })
      btns.eq(8).on('click', function () { editor.exec('codeBlock', 'js') })
      btns.eq(17).on('click', function () { editor.exec('undo') })
      btns.eq(18).on('click', function () { editor.exec('redo') })
      const fixed = $('.fixed')
      {
         const upimg = $('.fixed .upimg')
         const upimglink_input = $('#upimglink_input')
         const upimglink = $('#upimglink')
         upimglink.on('click', function () {
            const v = upimglink_input.val().trim()
            if (!v) return upimglink_input.addClass('error')
            editor.exec('addImage', {
               imageUrl: v,
               altText: ''
            })
            upimglink_input.val('')
            fixed.hide()
            upimg.hide()
         })
      }
      {
         const addtab = $('.fixed .addtab')
         const columnCount_input = $('#columnCount_input')
         const rowCount_input = $('#rowCount_input')
         const addTaber = $('#addTaber')
         addTaber.on('click', function () {
            const data = {
               columnCount: +columnCount_input.val().trim(),
               rowCount: +rowCount_input.val().trim()
            }
            if (!(data.columnCount > 0)) return columnCount_input.addClass('error')
            if (!(data.rowCount > 0)) return rowCount_input.addClass('error')
            editor.exec('addTable', data)
            fixed.hide()
            addtab.hide()
         })
      }
      {
         const addlink = $('.fixed .addlink')
         const linkUrl_input = $('#linkUrl_input')
         const linkText_input = $('#linkText_input')
         const addLinkq = $('#addLinkq')
         addLinkq.on('click', function () {
            const data = {
               linkUrl: linkUrl_input.val().trim(),
               linkText: linkText_input.val().trim()
            }
            if (!data.linkUrl) return linkUrl_input.addClass('error')
            if (!data.linkText) return linkText_input.addClass('error')
            editor.exec('addLink', data)
            linkUrl_input.val('')
            linkText_input.val('点击跳转')
            fixed.hide()
            addlink.hide()
         })
      }
   }
   {
      const header = $('header')
      const menu = $('.menu')
      $('.button-bar__button--navigation-bar-toggler').on('click', function () {
         if (menu[0].style.display) {
            header.show()
            menu.show()
         }
         else {
            header.hide()
            menu.hide()
         }
      })
      const preview = $('.toastui-editor-md-preview')
      $('.button-bar__button--side-preview-toggler').on('click', function () {
         if (preview[0].style.display) {
            preview.show()
         }
         else {
            preview.hide()
         }
      })
      const splitter = $('.toastui-editor-md-splitter')
      const editore = $('.toastui-editor')
      const edit = $('.edit')
      $('.button-bar__button--editor-toggler').on('click', function () {
         preview.css('width', '100%')
         preview.show()
         splitter.hide()
         editore.hide()
         edit.show()
      })
      edit.on('click', function () {
         preview.css('width', '')
         splitter.show()
         editore.show()
         edit.hide()
      })
      const footer = $('footer')
      $('.button-bar__button--status-bar-toggler').on('click', function () {
         if (footer[0].style.display) {
            footer.show()
         }
         else {
            footer.hide()
         }
      })
      {
         let active = true
         $('.button-bar__button--scroll-sync-toggler').on('click', function () {
            active = !active
            editor.exec('toggleScrollSync', {
               active
            })
         })
      }
   }
   // 底部信息栏
   {
      const ProseMirror = $('.toastui-editor-md-container .ProseMirror')
      const preview = $('.toastui-editor-md-preview')
      function updata() {
         $('#wordnum').text(editor.getMarkdown().length)
         $('#rownum').text(ProseMirror.children().length)
         $('#vwordnum').text(preview.text().length)
         $('#vcolumn').text(preview.find('tr, p, br').length)
      }
      function upcurrent() {
         const [[x, y]] = editor.getSelection()
         $('#current_row').text(x)
         $('#current_column').text(y)
      }
      updata()
      upcurrent()
      editor.on('change', function () {
         updata()
         upcurrent()
      })
      ProseMirror.on('selectstart', function () {
         setTimeout(upcurrent);
      })
   }
   // ajax
   {
      // 保存
      $('.button-save, .preservation').on('click', function () {
         const title = title_input.val()
         if (!title) return alterBlock('标题不能为空')
         const main = editor.getMarkdown()
         if (INFO) {
            const { id } = INFO
            $.post('/api/article/updata', {
               title,
               main,
               id
            }, res => {
               if (res.code == 200) {
                  $('.prestime_box').show()
                  const date = new Date(res.date)
                  $('#prestime').text(date.toLocaleString())
                  alterBlock('保存成功')
               } else {
                  alterBlock('保存失败，错误码：' + res.code)
               }
            })
         } else {
            $.post('/api/article/upload', {
               title,
               main
            }, res => {
               if (res.code == 200) {
                  INFO = { id: res.id }
                  replaceState()
                  $('.prestime_box').show()
                  const date = new Date(res.date)
                  $('#prestime').text(date.toLocaleString())
                  alterBlock('保存成功')
               } else {
                  alterBlock('保存失败，错误码：' + res.code)
               }
            })
         }
      })
      // 上传图片
      const upimg = $('#upimg input')
      const c = $('.upimg .c')
      upimg.on('change', function () {
         let { files } = this
         let formData = new FormData();
         for (let i = 0; i < files.length; i++) {
            let file = files[i];
            formData.append('files[' + i + ']', file, file.name);
         }
         $.ajax({
            url: '/api/upimage',
            type: 'post',
            data: formData,
            contentType: false,
            processData: false,
            success(res) {
               console.log(res);
               if (res.code == 200) {
                  res.files.forEach(a => {
                     editor.exec('addImage', {
                        imageUrl: '/userupimage/' + a.url,
                        altText: a.oldname
                     })
                  })
                  c.click()
               } else {
                  c.click()
                  alterBlock('上传失败，错误码：' + res.code)
               }
            }
         })
      })
      // 发布
      {
         const form = $('#push_form')[0]
         const cover_list = $('.cover-list')
         const cover = cover_list.find('.fmimage_box')
         // 收集表单信息
         function info() {
            const title = title_input.val()
            if (!title) return alterBlock('标题不能为空')
            const formData = new FormData(form)
            const cover_type = formData.get('cover_type')
            const le = cover_type == 2 ? 3 : cover_type
            for (let i = 0; i < le; i++) {
               const v = cover[i]
               if (!v.style.backgroundImage) return alterBlock('未上传封面')
               const input = $(v).find('input')[0]
               if (input.files[0]) {
                  formData.append('cover_' + i, input.files[0])
               } else {
                  formData.append('cover_' + i, $(v).data('url'))
               }
            }
            formData.append('id', INFO.id)

            const tag = formData.getAll('tag')
            formData.delete('tag')
            formData.append('tag', tag.join(' '))

            const classes = formData.getAll('class')
            formData.delete('class')
            formData.append('classif', classes.join(' '))
            return formData
         }
         async function post(bl) {
            const title = title_input.val()
            if (!title) return alterBlock('标题不能为空')
            let res
            if (INFO) {
               res = await $.post('/api/article/updata', {
                  id: INFO.id,
                  main: editor.getMarkdown(),
                  title: title_input.val()
               })
            } else {
               res = await $.post('/api/article/upload', {
                  main: editor.getMarkdown(),
                  title: title_input.val()
               })
               INFO = { id: res.id }
               replaceState()
            }
            if (res.code != 200) return alterBlock('出现未知错误，错误码：' + res.code)
            const res1 = await $.ajax({
               url: '/api/article/upinfo',
               type: 'post',
               data: info(),
               contentType: false,
               processData: false
            })
            if (res1.code == 200) {
               if (bl) {
                  const res2 = await $.post('/api/article/push', {
                     id: INFO.id
                  })
                  if (res2.code != 200) return alterBlock('出现未知错误，错误码：' + res2.code)
               }
               alterBlock('上传成功')
            } else {
               alterBlock('出现未知错误，错误码：' + res1.code)
            }
         }
         $('#up_send').on('click', async function () {
            await post()
         })
         $('#push_send').on('click', async function () {
            await post(true)
         })
      }
   }
   // 导入
   $('#import-markdown-file-input').on('change', async function () {
      const file = this.files[0]
      const text = await file.text()
      editor.setMarkdown(text)
      editor.moveCursorToStart()
      title_input.val(file.name.replace(/.md$/, ''))
      alterBlock('导入成功')
   })
   //导出
   const c = $('.fixed .exportd .c')
   const exportMarkdown_input = $('.exportMarkdown_input')
   const exportHTML_input = $('.exportHTML_input')
   // Markdown
   $('#exportMarkdown').on('click', function () {
      const name = exportMarkdown_input.val().trim()
      if (!name) return exportMarkdown_input.addClass('error')
      const url = URL.createObjectURL(new Blob([editor.getMarkdown()]))
      const filename = name + '.md'
      download(url, filename)
      c.click()
      alterBlock('导出成功' + filename)
   })
   // HTML
   $('#exportHTML').on('click', function () {
      const name = exportHTML_input.val().trim()
      if (!name) return exportHTML_input.addClass('error')
      const url = URL.createObjectURL(new Blob([editor.getHTML()]))
      const filename = name + '.html'
      download(url, filename)
      c.click()
      alterBlock('导出成功')
   })
})